package 力扣_滑动窗口.第二类模板;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author zx
 * @create 2022-05-21 18:29
 */
public class 滑动窗口的最大值_239 {
    /**
     * @return 代码好写,但是时间复杂度O(nlogK)
     */
    public int[] maxSlidingWindow(int[] nums, int k) {
        // 使用大顶堆
        PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] != o2[0] ? o2[0] - o1[0] : o2[1] - o1[1];
            }
        });
        for (int i = 0; i < k; ++i) {
            queue.offer(new int[]{nums[i], i});
        }
        int[] res = new int[nums.length - k + 1];
        res[0] = queue.peek()[0];
        int left = 0;
        for (int i = k;i < nums.length;i++) {
            // 先加入右边界,再淘汰左边界;再写入返回元素
            queue.offer(new int[]{nums[i],i});
            left = i - k;
            while (queue.peek()[1] <= left) {
                queue.poll();
            }
            res[i - k + 1] = queue.peek()[0];
        }
        return res;
    }

    /**
     * @return 测试用例改了,所以超时了
     */
    public int[] maxSlidingWindow3(int[] nums, int k) {
        //特殊情况
        if(nums.length == 0) {
            return new int[]{};
        }
        if(k == 1) {
            return  nums;
        }
        int right = 0,left = 0, count = 0, max = Integer.MIN_VALUE;
        int[] res = new int[nums.length - k + 1];
        while(right < nums.length) {
            int windowMax = nums[right];//windowMax是移入窗口的值，并记录窗口中最大值
            max = Math.max(windowMax,max);
            right++;
            while (right - left == k) {//达到窗口长度
                res[count++] = max;//该窗口最大值记录进数组
                int gun = nums[left];//gun是即将移出窗口的值
                if(gun == max){//如果移出的是最大值，将max改为剩下窗口内元素的最大值
                    int temp = Integer.MIN_VALUE;
                    for (int i = left + 1; i < right ; i++) {
                        if (nums[i] > temp) {
                            temp = nums[i];
                        }
                    }
                    max = temp;
                }
                left++;
            }
        }
        return res;
    }
}
